'use client';

import {
  type ChangeEvent,
  type FormEvent,
  useEffect,
  useRef,
  useState,
} from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IDifference, IPostStyle, IQueryPostDetails } from '@/interfaces';
import type {
  TBody,
  TStyleBackgroundColorMode,
  TStyleColorMode,
} from '@/types';
import { TStyleType } from '@/types';
import useToast from '@/hooks/useToast';
import {
  getDiffData,
  getFilterData,
  isEmpty,
  mergeObject,
  toCamelCase,
} from '@/lib/tool';
import {
  BADGE_BACKGROUND_COLOR_MODE,
  BADGE_COLOR_MODE,
  STYLE_BACKGROUND_COLOR_MODE,
  STYLE_COLOR_MODE,
  STYLE_TYPE,
} from '@/lib/constant';
import IroItem from '@/app/[locale]/admin/forum/post/other/IroItem';
import {
  createPostStyle,
  queryAllPostStylePreset,
  removePostStyle,
  updatePostStyle,
} from '@/services/api';
import classNames from 'classnames';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';

const defaultForm: any = {
  name: '',
  type: 'PRESET',
  icons: [],
  styles: {},
  classes: [],
  colorMode: 'DEFAULT',
  color: '#ffffff',
  backgroundColorMode: 'DEFAULT',
  backgroundColor: '#000000',
  useStyle: false,
  useClass: false,
};

export default function UpdatePostStyle(
  this: any,
  {
    details,
  }: {
    details: IQueryPostDetails;
  },
) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    name?: string;
    type?: TStyleType;
    icons?: string[];
    styles?: Record<string, string>;
    classes?: string[];
    colorMode?: TStyleColorMode;
    color?: string;
    backgroundColorMode?: TStyleBackgroundColorMode;
    backgroundColor?: string;
    useStyle?: boolean;
    useClass?: boolean;
  }>(defaultForm);
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [currentItemId, setCurrentItemId] = useState<number>();
  const [currentItem, setCurrentItem] = useState<IPostStyle>();
  const [currentRemoveItemId, setCurrentRemoveItemId] = useState<number>();
  const queryClient = useQueryClient();
  const selectColorModeRef = useRef<HTMLSelectElement>(null);
  const selectBackgroundColorModeRef = useRef<HTMLSelectElement>(null);
  const [selectColorMode, setSelectColorMode] = useState('HEX');
  const [selectBackgroundColorMode, setSelectBackgroundColorMode] =
    useState('HEX');
  const [usePreset, setUsePreset] = useState('-1');
  const [styleForm, setStyleForm] = useState({
    key: '',
    value: '',
  });

  const createPostStyleMutation = useMutation(
    async (
      variables: TBody<{
        postId: number;
        name: string;
        type: string;
      }>,
    ) => {
      await createPostStyle(variables);
      await queryClient.invalidateQueries([
        '/forum',
        '/posts',
        details.basic.id,
        '/details',
      ]);
    },
  );
  const updatePostStyleMutation = useMutation(
    async (
      variables: TBody<{
        name?: string;
        type?: string;
        colorMode?: string;
        color?: string;
        backgroundColorMode?: string;
        backgroundColor?: string;
        icons?: string[];
        styles?: Record<string, string>;
        classes?: string[];
        useStyle?: boolean;
        useClass?: boolean;
        postId?: number;
      }>,
    ) => {
      await updatePostStyle(variables);
      await queryClient.invalidateQueries([
        '/forum',
        '/posts',
        details.basic.id,
        '/details',
      ]);
    },
  );
  const removePostStyleMutation = useMutation(
    async (variables: TBody<void>) => {
      await removePostStyle(variables);
      await queryClient.invalidateQueries([
        '/forum',
        '/posts',
        details.basic.id,
        '/details',
      ]);
    },
  );
  const queryAllPostStylePresetQuery = useQuery(
    ['/forum', '/styles', '/preset'],
    async () => {
      return (await queryAllPostStylePreset()) as IPostStyle[];
    },
  );

  useEffect(() => {
    const differences = diff(currentItem ? currentItem : defaultForm, form);
    setDifferenceData(differences);
  }, [currentItem, form]);
  useEffect(() => {
    if (currentItem) {
      setCurrentItem({
        ...currentItem,
        ...details.basic.styles.find((item) => item.id === currentItem.id),
      });
    }
  }, [details]);

  function onChangeForm(
    e: ChangeEvent<HTMLSelectElement | HTMLTextAreaElement | HTMLInputElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'useStyle') {
      setForm({ ...form, useStyle: value === 'true' });
    } else if (name === 'useClass') {
      setForm({ ...form, useClass: value === 'true' });
    } else if (name === 'icons') {
      setForm({
        ...form,
        icons: value
          .replaceAll('，', ',')
          .split(',')
          .map((item) => item.trim()),
      });
    } else if (name === 'classes') {
      setForm({
        ...form,
        classes: value
          .replaceAll('，', ',')
          .split(',')
          .map((item) => item.trim()),
      });
    } else if (name === 'selectColorMode') {
      setSelectColorMode(value);
    } else if (name === 'selectBackgroundColorMode') {
      setSelectBackgroundColorMode(value);
    } else if (name === 'color') {
      setForm({
        ...form,
        [name]: value,
        useStyle: true,
        styles: { ...form.styles, color: value },
      });
    } else if (name === 'backgroundColor') {
      setForm({
        ...form,
        [name]: value,
        useStyle: true,
        styles: { ...form.styles, backgroundColor: value },
      });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  function onChangeUsePreset(e: ChangeEvent<HTMLSelectElement>) {
    const value = e.target.value;

    if (value === '-1') {
      setForm({
        ...mergeObject(currentItem, form),
        name: form.name,
        type: form.type,
      });
    } else if (queryAllPostStylePresetQuery.data) {
      const find = queryAllPostStylePresetQuery.data.find(
        (item) => item.id + '' === value,
      );
      if (find) {
        setForm({
          ...mergeObject(find, form),
          name: form.name,
          type: form.type,
        });
      } else {
        show({
          type: 'DANGER',
          message: '选择的预设不存在，请尝试关闭重新打开',
        });
        return;
      }
    }

    setUsePreset(value);
  }

  function onChangeStyles(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setStyleForm({ ...styleForm, [name]: value });
  }

  function onClickDashStyle(key: string) {
    const styles = { ...form.styles };
    delete styles[key];
    setForm({
      ...form,
      styles,
    });
  }

  function onClickPlusStyle() {
    const { key, value } = styleForm;

    if (!key) {
      show({
        type: 'DANGER',
        message: '名称不能为空',
      });
      return;
    }

    if (!value) {
      show({
        type: 'DANGER',
        message: '内容不能为空',
      });
      return;
    }

    setForm({
      ...form,
      styles: { ...form.styles, [toCamelCase(key)]: value },
    });
    setStyleForm({
      key: '',
      value: '',
    });
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      if (currentItemId) {
        if (
          body.type &&
          body.type === 'NAME' &&
          details.basic.styles.find((item) => item.type === body.type)
        ) {
          delete body.type;
        }

        body.icons = form.icons;
        body.styles = form.styles;
        body.classes = form.classes;

        if (body.type === 'NAME') {
          body.postId === details.basic.id;
        }

        await updatePostStyleMutation.mutateAsync({
          id: currentItemId,
          data: body,
        });
      } else {
        await createPostStyleMutation.mutateAsync({
          data: {
            name: body.name,
            postId: details.basic.id,
            type: body.type ? body.type : 'PRESET',
          },
        });

        setForm(defaultForm);
      }

      await queryAllPostStylePresetQuery.refetch({ throwOnError: true });
      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      if (currentItemId) {
        updatePostStyleMutation.reset();
      } else {
        createPostStyleMutation.reset();
      }

      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onClickItem(item: IPostStyle) {
    setCurrentItemId(item.id);
    setCurrentItem(item);
    setForm(mergeObject(item, form));
  }

  function onClickCancel() {
    setCurrentItemId(undefined);
    setForm({ ...form, ...defaultForm });
  }

  async function onClickRemove(item: IPostStyle) {
    try {
      setCurrentRemoveItemId(item.id);

      await removePostStyleMutation.mutateAsync({
        id: item.id,
      });

      await queryAllPostStylePresetQuery.refetch({ throwOnError: true });
      setCurrentItemId(undefined);
      clearData();
      show({
        type: 'SUCCESS',
        message: '删除完成',
      });
    } catch (e) {
      removePostStyleMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
    setCurrentRemoveItemId(undefined);
  }

  function checkForm() {
    const name = form.name;

    if (!name) {
      throw '样式名称不能为空';
    }

    if (
      !currentItemId &&
      form.type === 'NAME' &&
      details.basic.styles.find((item) => item.type === 'NAME')
    ) {
      throw '该样式类型已存在，请尝试更新';
    }
  }

  function changeColorCallback(color: string) {
    if (!color) {
      return;
    }

    setForm({
      ...form,
      color,
      useStyle: true,
      styles: { ...form.styles, color },
    });
  }

  function changeBackgroundColorCallback(color: string) {
    if (!color) {
      return;
    }

    setForm({
      ...form,
      backgroundColor: color,
      useStyle: true,
      styles: { ...form.styles, backgroundColor: color },
    });
  }

  if (queryAllPostStylePresetQuery.data) {
    const data = [
      ...queryAllPostStylePresetQuery.data,
      ...details.basic.styles,
    ];

    return (
      <div className="row">
        <div className="col">
          <div className="vstack gap-4">
            <div>
              <div className="table-responsive">
                <table className="table table-hover align-middle">
                  <thead>
                    <tr className="text-nowrap">
                      <th scope="col" className="w-10 fw-normal">
                        名称
                      </th>
                      <th scope="col" className="w-10 fw-normal">
                        类型
                      </th>
                      <th scope="col" className="w-10 fw-normal">
                        颜色
                      </th>
                      <th scope="col" className="w-10 fw-normal">
                        背景颜色
                      </th>
                      <th scope="col" className="w-10 fw-normal">
                        使用类名
                      </th>
                      <th scope="col" className="w-10 fw-normal">
                        使用样式
                      </th>
                      <th scope="col" className="w-10"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.map((item) => {
                      return (
                        <tr
                          key={item.id}
                          className={classNames(
                            'text-nowrap',
                            currentItemId === item.id ? 'table-active' : false,
                          )}
                        >
                          <td
                            className="cursor-pointer"
                            onClick={onClickItem.bind(this, item)}
                          >
                            <div
                              className={classNames(
                                item.useClass &&
                                  item.classes &&
                                  item.classes.length > 0
                                  ? item.classes
                                  : false,
                                'hstack gap-2',
                              )}
                              style={
                                item.useStyle &&
                                item.styles &&
                                Object.keys(item.styles).length > 0
                                  ? item.styles
                                  : {}
                              }
                            >
                              {item.icons.map((value) => {
                                return (
                                  <i
                                    key={value}
                                    className={classNames('bi', `bi-${value}`)}
                                  ></i>
                                );
                              })}
                              <span>{item.name}</span>
                            </div>
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickItem.bind(this, item)}
                          >
                            {STYLE_TYPE[item.type]}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickItem.bind(this, item)}
                          >
                            {item.color
                              ? `${STYLE_COLOR_MODE[item.colorMode]} (${
                                  item.color
                                })`
                              : STYLE_COLOR_MODE[item.colorMode]}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickItem.bind(this, item)}
                          >
                            {item.backgroundColor
                              ? `${
                                  STYLE_BACKGROUND_COLOR_MODE[
                                    item.backgroundColorMode
                                  ]
                                } (${item.backgroundColor})`
                              : STYLE_BACKGROUND_COLOR_MODE[
                                  item.backgroundColorMode
                                ]}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickItem.bind(this, item)}
                          >
                            {item.useClass ? '是' : '否'}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickItem.bind(this, item)}
                          >
                            {item.useStyle ? '是' : '否'}
                          </td>
                          <td>
                            {currentItemId === item.id && (
                              <button
                                onClick={onClickCancel}
                                className="btn btn-sm btn-light me-2"
                                type="button"
                              >
                                取消
                              </button>
                            )}

                            <button
                              disabled={
                                currentRemoveItemId === item.id &&
                                removePostStyleMutation.isLoading
                              }
                              onClick={onClickRemove.bind(this, item)}
                              className="btn btn-sm btn-danger"
                              type="button"
                            >
                              {currentRemoveItemId === item.id &&
                              removePostStyleMutation.isLoading ? (
                                <span
                                  className="spinner-border spinner-border-sm me-2"
                                  role="status"
                                  aria-hidden="true"
                                ></span>
                              ) : (
                                <i className="bi bi-trash me-2"></i>
                              )}
                              删除
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {data.length === 0 && <div className="text-muted">暂无样式</div>}
            </div>

            {form.name && (
              <div className="card position-relative">
                <div className="card-body text-center">
                  <div
                    className="position-absolute text-muted"
                    style={{
                      left: '-1rem',
                      top: '-0.7rem',
                      transform: 'skew(15deg)',
                    }}
                  >
                    预览
                  </div>
                  <div
                    className={classNames(
                      form.useClass && form.classes && form.classes.length > 0
                        ? form.classes
                        : false,
                      'hstack gap-2 justify-content-center',
                    )}
                    style={
                      form.useStyle &&
                      form.styles &&
                      Object.keys(form.styles).length > 0
                        ? form.styles
                        : {}
                    }
                  >
                    {(form.icons || []).map((value) => {
                      return (
                        <i
                          key={value}
                          className={classNames('bi', `bi-${value}`)}
                        ></i>
                      );
                    })}
                    <span>{details.basic.name}</span>
                  </div>
                </div>
              </div>
            )}

            <form onSubmit={onClickSave} className="vstack gap-4">
              {currentItem && currentItem.type !== 'PRESET' && (
                <div>
                  <label className="form-label">使用预设</label>
                  <select
                    name="usePreset"
                    value={usePreset}
                    onChange={onChangeUsePreset}
                    className="form-select"
                    aria-label="usePreset"
                    placeholder="请选择是否使用预设"
                  >
                    <option value="-1">默认</option>
                    {queryAllPostStylePresetQuery.data.map((item) => {
                      return (
                        <option key={item.id} value={item.id + ''}>
                          {item.name}
                        </option>
                      );
                    })}
                  </select>
                </div>
              )}

              <div>
                <label className="form-label">名称</label>
                <input
                  type="text"
                  className="form-control"
                  name="name"
                  value={form.name}
                  onChange={onChangeForm}
                  aria-describedby="name"
                  placeholder="请输入样式名称"
                />
              </div>

              <div>
                <label className="form-label">类型</label>
                <select
                  name="type"
                  value={form.type}
                  onChange={onChangeForm}
                  className="form-select"
                  aria-label="type"
                  placeholder="请选择样式类型"
                >
                  <option value="PRESET">预设</option>
                  <option value="NAME">名称</option>
                </select>
              </div>

              {currentItemId && (
                <>
                  <div>
                    <label className="form-label">颜色模式</label>
                    <div className="form-control user-select-none">
                      {Object.keys(BADGE_COLOR_MODE).map((item) => {
                        return (
                          <div
                            key={item}
                            className="form-check form-check-inline"
                          >
                            <input
                              id={`yw-badge-colorMode-${item}`}
                              name="colorMode"
                              className="form-check-input"
                              type="radio"
                              onChange={onChangeForm}
                              value={item}
                              checked={form.colorMode === item}
                            />
                            <label
                              className="form-check-label"
                              htmlFor={`yw-badge-colorMode-${item}`}
                            >
                              {BADGE_COLOR_MODE[item]}
                            </label>
                          </div>
                        );
                      })}
                    </div>
                  </div>

                  {form.colorMode === 'CUSTOM' && (
                    <div>
                      <label className="form-label">颜色</label>
                      <div className="row align-items-center gap-4">
                        <div className="col-4">
                          <div className="vstack gap-4">
                            <div className="row gap-4 align-items-center">
                              <div className="col-2"></div>
                              <div className="col">
                                <select
                                  ref={selectColorModeRef}
                                  name="selectColorMode"
                                  value={selectColorMode}
                                  onChange={onChangeForm}
                                  className="form-select"
                                  aria-label="selectColorMode"
                                  placeholder="请选择颜色输出类型"
                                >
                                  <option value="HEX">HEX</option>
                                  <option value="RGB">RGB</option>
                                  <option value="RGBA">RGBA</option>
                                  <option value="HSL">HSL</option>
                                  <option value="HSLA">HSLA</option>
                                </select>
                              </div>
                            </div>

                            <input
                              type="text"
                              className="form-control"
                              name="color"
                              value={form.color}
                              onChange={onChangeForm}
                              aria-describedby="color"
                              placeholder="请输入或选择颜色"
                            />

                            <div className="form-text">
                              滑块条依次为：色调、饱和度、值、透明度、冷暖
                            </div>
                          </div>
                        </div>
                        <div className="col-7">
                          <IroItem
                            inputColor={form.color}
                            selectColorModeRef={selectColorModeRef}
                            changeColorCallback={changeColorCallback}
                          />
                        </div>
                      </div>
                    </div>
                  )}

                  {form.name &&
                    (form.colorMode === 'CUSTOM' ||
                      form.backgroundColorMode === 'CUSTOM') && (
                      <div className="card position-relative">
                        <div className="card-body text-center">
                          <div
                            className="position-absolute text-muted"
                            style={{
                              left: '-1rem',
                              top: '-0.7rem',
                              transform: 'skew(15deg)',
                            }}
                          >
                            预览
                          </div>
                          <div
                            className={classNames(
                              form.useClass &&
                                form.classes &&
                                form.classes.length > 0
                                ? form.classes
                                : false,
                              'hstack gap-2 justify-content-center',
                            )}
                            style={
                              form.useStyle &&
                              form.styles &&
                              Object.keys(form.styles).length > 0
                                ? form.styles
                                : {}
                            }
                          >
                            {(form.icons || []).map((value) => {
                              return (
                                <i
                                  key={value}
                                  className={classNames('bi', `bi-${value}`)}
                                ></i>
                              );
                            })}
                            <span>{details.basic.name}</span>
                          </div>
                        </div>
                      </div>
                    )}

                  <div>
                    <label className="form-label">背景颜色模式</label>
                    <div className="form-control user-select-none">
                      {Object.keys(BADGE_BACKGROUND_COLOR_MODE).map((item) => {
                        return (
                          <div
                            key={item}
                            className="form-check form-check-inline"
                          >
                            <input
                              id={`yw-badge-backgroundColorMode-${item}`}
                              name="backgroundColorMode"
                              className="form-check-input"
                              type="radio"
                              onChange={onChangeForm}
                              value={item}
                              checked={form.backgroundColorMode === item}
                            />
                            <label
                              className="form-check-label"
                              htmlFor={`yw-badge-backgroundColorMode-${item}`}
                            >
                              {BADGE_BACKGROUND_COLOR_MODE[item]}
                            </label>
                          </div>
                        );
                      })}
                    </div>
                  </div>

                  {form.backgroundColorMode === 'CUSTOM' && (
                    <div>
                      <label className="form-label">背景颜色</label>
                      <div className="row align-items-center gap-4">
                        <div className="col-4">
                          <div className="vstack gap-4">
                            <div className="row gap-4 align-items-center">
                              <div className="col-2"></div>
                              <div className="col">
                                <select
                                  ref={selectBackgroundColorModeRef}
                                  name="selectBackgroundColorMode"
                                  value={selectBackgroundColorMode}
                                  onChange={onChangeForm}
                                  className="form-select"
                                  aria-label="selectBackgroundColorMode"
                                  placeholder="请选择背景颜色输出类型"
                                >
                                  <option value="HEX">HEX</option>
                                  <option value="RGB">RGB</option>
                                  <option value="RGBA">RGBA</option>
                                  <option value="HSL">HSL</option>
                                  <option value="HSLA">HSLA</option>
                                </select>
                              </div>
                            </div>

                            <input
                              type="text"
                              className="form-control"
                              name="backgroundColor"
                              value={form.backgroundColor}
                              onChange={onChangeForm}
                              aria-describedby="backgroundColor"
                              placeholder="请输入或选择背景颜色"
                            />

                            <div className="form-text">
                              滑块条依次为：色调、饱和度、值、透明度、冷暖
                            </div>
                          </div>
                        </div>
                        <div className="col-7">
                          <IroItem
                            inputColor={form.backgroundColor}
                            selectColorModeRef={selectBackgroundColorModeRef}
                            changeColorCallback={changeBackgroundColorCallback}
                          />
                        </div>
                      </div>
                    </div>
                  )}

                  <div>
                    <label className="form-label">
                      <span>图标</span>
                      <span className="ms-2">
                        (
                        <a
                          target="_blank"
                          href="https://icons.getbootstrap.com"
                        >
                          点击查看图标
                        </a>
                        )
                      </span>
                    </label>
                    <textarea
                      rows={1}
                      className="form-control"
                      name="icons"
                      value={form.icons?.join(', ')}
                      onChange={onChangeForm}
                      aria-describedby="icons"
                      placeholder="请输入图标名称，多个图标名称使用逗号分隔"
                    />
                  </div>

                  <div>
                    <label className="form-label">使用类名</label>
                    <select
                      name="useClass"
                      value={form.useClass + ''}
                      onChange={onChangeForm}
                      className="form-select"
                      aria-label="useClass"
                      placeholder="请选择是否使用类名"
                    >
                      <option value="false">否</option>
                      <option value="true">是</option>
                    </select>
                  </div>

                  {form.useClass && (
                    <div>
                      <label className="form-label">类名</label>
                      <textarea
                        rows={1}
                        className="form-control"
                        name="classes"
                        value={form.classes?.join(', ')}
                        onChange={onChangeForm}
                        aria-describedby="classes"
                        placeholder="请输入类名，多个类名使用逗号分隔"
                      />
                    </div>
                  )}

                  <div>
                    <label className="form-label">使用样式</label>
                    <select
                      name="useStyle"
                      value={form.useStyle + ''}
                      onChange={onChangeForm}
                      className="form-select"
                      aria-label="useStyle"
                      placeholder="请选择是否使用样式"
                    >
                      <option value="false">否</option>
                      <option value="true">是</option>
                    </select>
                  </div>

                  {form.useStyle && (
                    <div className="vstack gap-2">
                      <div>
                        <label className="form-label">样式</label>
                        <div className="vstack gap-2">
                          {form.styles &&
                            Object.keys(form.styles).map((value) => {
                              return (
                                <div key={value} className="hstack gap-4">
                                  <input
                                    readOnly
                                    type="text"
                                    className="form-control"
                                    name="key"
                                    value={value}
                                    aria-describedby="key"
                                  />
                                  <input
                                    readOnly
                                    type="text"
                                    className="form-control"
                                    name="value"
                                    value={(form.styles || {})[value] || ''}
                                    aria-describedby="value"
                                  />
                                  <button
                                    onClick={onClickDashStyle.bind(this, value)}
                                    type="button"
                                    className="btn w-25 btn-danger"
                                  >
                                    <i className="bi bi-dash-lg"></i>
                                  </button>
                                </div>
                              );
                            })}
                        </div>
                      </div>
                      <div className="hstack gap-4 mb-4">
                        <input
                          type="text"
                          className="form-control"
                          name="key"
                          value={styleForm.key}
                          onChange={onChangeStyles}
                          aria-describedby="key"
                          placeholder="请输入名称，使用驼峰式命名，如：backgroundColor"
                        />
                        <input
                          type="text"
                          className="form-control"
                          name="value"
                          value={styleForm.value}
                          onChange={onChangeStyles}
                          aria-describedby="value"
                          placeholder="请输入内容"
                        />
                        <button
                          onClick={onClickPlusStyle}
                          type="button"
                          className="btn w-25 btn-primary"
                        >
                          <i className="bi bi-plus-lg"></i>
                        </button>
                      </div>
                    </div>
                  )}
                </>
              )}

              <button
                type="submit"
                disabled={
                  createPostStyleMutation.isLoading ||
                  updatePostStyleMutation.isLoading
                }
                className={classNames(
                  'btn w-25 my-4',
                  currentItemId ? 'btn-success' : 'btn-primary',
                )}
              >
                {(createPostStyleMutation.isLoading ||
                  updatePostStyleMutation.isLoading) && (
                  <span
                    className="spinner-border spinner-border-sm me-2"
                    role="status"
                    aria-hidden="true"
                  ></span>
                )}
                {currentItemId ? '更新' : '添加'}
              </button>
            </form>
          </div>
        </div>
      </div>
    );
  }

  if (queryAllPostStylePresetQuery.error) {
    return <Alert message={queryAllPostStylePresetQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
